package com.dg.cuckoo.admin.service.impl;

import com.dg.cuckoo.admin.dto.basicInformation.constructionUnit.ConstructionUnitDto;
import com.dg.cuckoo.admin.dto.basicInformation.permissionSettings.UnitTypeDto;
import com.dg.cuckoo.admin.dto.basicInformation.userInfo.UserInfoDto;
import com.dg.cuckoo.admin.dto.basicInformation.userInfo.UserInfoRelatedDto;
import com.dg.cuckoo.admin.repository.ConstructionRepository;
import com.dg.cuckoo.admin.repository.UnitTypeRepository;
import com.dg.cuckoo.admin.repository.UserInfoRelatedRepository;
import com.dg.cuckoo.admin.repository.UserInfoRepository;
import com.dg.cuckoo.admin.service.ConstructionService;
import com.dg.cuckoo.admin.service.ProjectInfoServer;
import com.dg.cuckoo.admin.service.UserInfoService;
import com.dg.cuckoo.admin.vo.FreeVo;
import com.dg.cuckoo.admin.vo.FreeVoT;
import com.dg.cuckoo.admin.vo.UserInfoVo;
import com.dg.cuckoo.core.ServiceException;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

@Service
public class UserInfoServiceimpl implements UserInfoService {

    @Autowired
    private UserInfoRepository userInfoRepository;
    @Autowired
    private ProjectInfoServer projectInfoServer;
    @Autowired
    private UnitTypeRepository unitTypeRepository;
    @Autowired
    private ConstructionRepository constructionRepository;
    @Autowired
    private UserInfoRelatedRepository userInfoRelatedRepository;
    @Autowired
    private ConstructionService constructionService;

    @Override
    public String organizationInfo() {
//        String utils = JSONObject.fromObject(projectInfoServer.clickUnitInfo()).getString("utils");//建设单位树
//
//        List<UnitTypeDto> all = unitTypeRepository.findAll();
//        List<String> typeName=new ArrayList<>();                //所有的建设单位类型
//        for(UnitTypeDto a:all){
//            typeName.add(a.getTypeName());
//        }
//
//        List<UserInfoDto> userInfos = userInfoRepository.findAll();
//        List<String> tool=new ArrayList<>();                    //获取用户信息中所有的单位名称
//        List<String> username=new ArrayList<>();                //获取用户名称
//        for(UserInfoDto d:userInfos){
//            for(String s:typeName){
//                if(d.getCompanyName().equals(s)){
//                    tool.add(d.getCompanyName());
//                }else {
//                    username.add(d.getUserName());
//                }
//            }
//        }
//
//        typeName.addAll(tool);
//        List newList = typeName.stream().distinct().collect(Collectors.toList());//去重后得到完整的是否可以打开 建设单位
//        JSONObject json = new JSONObject();
//        json.put("openUnit",newList);           //是否可以打开的建设单位信息
//        json.put("utils",utils);                //建设单位树信息
//        json.put("username",username);          //互补的用户名称信息
//        return json.toString();
        String[] constructionName=JSONObject.fromObject(projectInfoServer.clickUserInfo()).getString("userName").replace("[","").replace("]","").replace("\"","").split(",");
        List<UserInfoVo> freeVos=new ArrayList<>();
        for(String s:constructionName){
            List<String> list = constructionService.byUnitType(s);//组织结构二级标签
            List<FreeVoT> freeVos1=new ArrayList<>();
            for (String unitName:list){
                List<UserInfoRelatedDto> byCompanyName = userInfoRelatedRepository.findByCompanyName(unitName);
                List<UserInfoDto> userInfoDtos=new ArrayList<>();
                for(UserInfoRelatedDto u:byCompanyName){
                    Optional<UserInfoDto> userInfoDto = userInfoRepository.findById(u.getUserId());
                    userInfoDto.ifPresent(userInfoDtos::add);
//                    if (userInfoRepository.findById(u.getUserId()).get() != null){
//                        userInfoDtos.add(userInfoRepository.findById(u.getUserId()).get());
//                    }else {
//                        continue;
//                    }
                }
                freeVos1.add(new FreeVoT(unitName,userInfoDtos));
            }
            freeVos.add(new UserInfoVo(s,userInfoRepository.findByCompanyName(s),freeVos1));
        }
        JSONObject json = new JSONObject();
        json.put("freeVos",freeVos);//树和里面的内容
        List<UserInfoDto> list = userInfoRepository.findByCompanyName("");
        json.put("list",list);//建设单位为空的信息
        return json.toString();
    }

    @Override
    public void save(UserInfoDto dto) {
        dto=checkSave(dto);
        UserInfoDto save = userInfoRepository.save(dto);
        relatedSave(save.getId(),dto.getCompanyName());
    }

    @Override
    public UserInfoDto openUserInfo(String id) {
        if(id==null){
            throw new ServiceException("请选择用户");
        }
        return userInfoRepository.findById(id).get();
    }

    @Override
    public void delect(String id) {
        if(id==null){
            throw new ServiceException("请选择用户");
        }
        userInfoRepository.deleteById(id);
        userInfoRelatedRepository.delete(userInfoRelatedRepository.findByUserId(id));
    }

    @Override
    public void update(UserInfoDto dto,String id) {
        if(id==null){
            throw new ServiceException("请选择用户");
        }
        dto.setId(id);
        UserInfoDto save = userInfoRepository.save(dto);
        userInfoRelatedRepository.delete(userInfoRelatedRepository.findByUserId(id));
        relatedSave(save.getId(),dto.getCompanyName());
    }

    @Override
    public String tissueTwo(String unitType) {
        if(unitType==null){
            throw new ServiceException("请点击组织架构");
        }
        List<ConstructionUnitDto> dtos = constructionRepository.findByUnitType(unitType);
        List<UserInfoDto> users = userInfoRepository.findAll();

        List<String> name=new ArrayList<>();
        for(ConstructionUnitDto d:dtos){
            name.add(d.getConstructionName());
        }

        List<String> contain=new ArrayList<>();
        for(UserInfoDto u:users){
            for(String n:name){
                if(u.getCompanyName().equals(n)){
                    contain.add(u.getUserName());
                }
            }

        }
        List newList = contain.stream().distinct().collect(Collectors.toList());//去重后得到是否拥有包含的二级标签

        JSONObject json = new JSONObject();
        json.put("name",name);      //二级标签的名称集合
        json.put("contain",newList);//二级标签是否存在包含
        return json.toString();
    }

    @Override
    public List<UserInfoDto> tissueThree(String unitType) {
        if(unitType==null){
            throw new ServiceException("请点击组织架构");
        }
        List<UserInfoDto> dtos = userInfoRepository.findByCompanyName(unitType);
        return dtos;
    }

    public UserInfoDto checkSave(UserInfoDto dto){
        if(dto.getUserName()==null){
            throw new ServiceException("请输入用户名称");
        }
        if(userInfoRepository.findByUserName(dto.getUserName())!=null){
            throw new ServiceException("用户名称已存在，请重新输入");
        }
        if(dto.getUserShortcode()==null){
            throw new ServiceException("请输入用户简码");
        }
        if(dto.getUserCoding()==null){
            throw new ServiceException("请输入用户编码");
        }
        if(userInfoRepository.findByUserCoding(dto.getUserCoding())!=null){
            throw new ServiceException("用户编码已存在，请重新输入");
        }
        if(dto.getCompanyName()==null){
            dto.setCompanyName("");
        }
        return dto;
    }

    public void relatedSave(String userId,String companyName){
        UserInfoRelatedDto dto = new UserInfoRelatedDto();
        dto.setUserId(userId);
        dto.setCompanyName(companyName);
        userInfoRelatedRepository.save(dto);
    }



}
